 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.subway.rca.entity.ViewCkClearAccountDetailSummary;
import com.zdkj.subway.rca.mapper.ViewCkClearAccountDetailSummaryMapper;
import com.zdkj.subway.rca.service.ViewCkClearAccountDetailSummaryService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * VIEW
 *
 * @author stw
 * @date 2020-12-14 15:41:17
 */
@Service
public class ViewCkClearAccountDetailSummaryServiceImpl extends ServiceImpl<ViewCkClearAccountDetailSummaryMapper, ViewCkClearAccountDetailSummary> implements ViewCkClearAccountDetailSummaryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ViewCkClearAccountDetailSummaryServiceImpl.class);
    @Override
    public List<ViewCkClearAccountDetailSummary> listViewCkClearAccountDetailSummary(String startDate, String endDate, String operators, String lineCode) {
        ViewCkClearAccountDetailSummary viewCkClearAccountDetailSummary = new ViewCkClearAccountDetailSummary();
        viewCkClearAccountDetailSummary.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        viewCkClearAccountDetailSummary.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        viewCkClearAccountDetailSummary.setOperators(operators);
        viewCkClearAccountDetailSummary.setLineCode(lineCode);
        QueryWrapper<ViewCkClearAccountDetailSummary> queryWrappers = Wrappers.query(viewCkClearAccountDetailSummary);
        queryWrappers.orderByAsc("OPERATORS");
        queryWrappers.orderByAsc("CAST(LINE_CODE AS SIGNED)");
        List<ViewCkClearAccountDetailSummary> list = this.list(queryWrappers);
        List<ViewCkClearAccountDetailSummary> listNew = new ArrayList<>();

        String operatorsName = null;
        for(ViewCkClearAccountDetailSummary obj : list){
            if(!obj.getOperatorsName().equals(operatorsName) && operatorsName != null){
                ViewCkClearAccountDetailSummary sum = getSum(operatorsName, list);
                listNew.add(sum);
            }
            operatorsName = obj.getOperatorsName();
            listNew.add(obj);
        }
        if(list.size() > 0) { //最后一个运营商
            ViewCkClearAccountDetailSummary sum = getSum(operatorsName, list);
            listNew.add(sum);
        }

        ViewCkClearAccountDetailSummary sumAll  = getSum("合计",list);
        sumAll.setLineName("--");
        listNew.add(sumAll);
        return listNew;
    }

    private ViewCkClearAccountDetailSummary getSum(String operatorsName,List<ViewCkClearAccountDetailSummary> list){
        ViewCkClearAccountDetailSummary sumViewCkClearAccountDetailSummary = new ViewCkClearAccountDetailSummary();
        if("合计".equals(operatorsName)){
            sumViewCkClearAccountDetailSummary.setOperatorsName(operatorsName);
        }
        sumViewCkClearAccountDetailSummary.setLineName("小计");
        BigDecimal paidinOnewaySum = new BigDecimal("0");
        BigDecimal receivableOnewaySum = new BigDecimal("0");
        BigDecimal receivableOnewayAccSum = new BigDecimal("0");
        BigDecimal receivableOnewayAgreeClean = new BigDecimal("0");
        BigDecimal receivableOnewayReceivedClean = new BigDecimal("0");
        BigDecimal countingTicket = new BigDecimal("0");
        BigDecimal dailyTicket = new BigDecimal("0");
        BigDecimal commemorativeTicket = new BigDecimal("0");
        BigDecimal catSystemClean = new BigDecimal("0");
        BigDecimal catAgreeClean = new BigDecimal("0");
        BigDecimal catSubtotal = new BigDecimal("0");
        BigDecimal trafficCardSystemClean = new BigDecimal("0");
        BigDecimal trafficCardAgreeClean = new BigDecimal("0");
        BigDecimal trafficCardCatSubtotal = new BigDecimal("0");
        BigDecimal qrCodeTicket = new BigDecimal("0");
        BigDecimal systemClean = new BigDecimal("0");
        BigDecimal qrCodeTicketAgreeClean = new BigDecimal("0");
        BigDecimal qrSubtotal = new BigDecimal("0");
        BigDecimal faceTicketCcb = new BigDecimal("0");
        BigDecimal faceTicketSystemClean = new BigDecimal("0");
        BigDecimal faceTicketAgreeClean = new BigDecimal("0");
        BigDecimal faceSubtotal = new BigDecimal("0");
        BigDecimal incomeSubtotal = new BigDecimal("0");
        BigDecimal systemCleanSum = new BigDecimal("0");
        BigDecimal systemCleanSumRatio = new BigDecimal("0");
        BigDecimal paidinReceivable = new BigDecimal("0");
        BigDecimal receivableAcc = new BigDecimal("0");

        BigDecimal paidinPreticket = new BigDecimal("0");
        BigDecimal paidinInternetTicket = new BigDecimal("0");
        BigDecimal paidinOnewayTicket = new BigDecimal("0");
        BigDecimal paidinLongPayment = new BigDecimal("0");
        BigDecimal receivablePreticket = new BigDecimal("0");
        BigDecimal receivableInternetTicket = new BigDecimal("0");
        BigDecimal receivableOnewayTicket = new BigDecimal("0");
        BigDecimal receivableOnewayFare = new BigDecimal("0");
        BigDecimal receivableOnewayRefund = new BigDecimal("0");
        BigDecimal receivableOnewayOffset = new BigDecimal("0");
        BigDecimal payableOutClean = new BigDecimal("0");
        BigDecimal payablePreticketClean = new BigDecimal("0");
        BigDecimal payableOnewayClean = new BigDecimal("0");
        BigDecimal payableOnewayCleanFare = new BigDecimal("0");
        BigDecimal payableOnewayCleanOnlySale = new BigDecimal("0");
        BigDecimal receivableOnewaySubTotal = new BigDecimal("0");
        BigDecimal catTicketPay = new BigDecimal("0");
        BigDecimal trafficCardPay = new BigDecimal("0");
        BigDecimal qrConnectivitySubTotal = new BigDecimal("0");
        BigDecimal qrCodeSubTotal = new BigDecimal("0");

        for(ViewCkClearAccountDetailSummary  obj : list){
            if(operatorsName.equals("合计") || operatorsName.equals(obj.getOperatorsName())){
                paidinOnewaySum = paidinOnewaySum.add(obj.getPaidinOnewaySum());
                receivableOnewaySum =  receivableOnewaySum.add(obj.getReceivableOnewaySum());
                receivableOnewayAccSum = receivableOnewayAccSum.add(obj.getReceivableOnewayAccSum());
                receivableOnewayAgreeClean = receivableOnewayAgreeClean.add(obj.getReceivableOnewayAgreeClean());
                receivableOnewayReceivedClean = receivableOnewayReceivedClean.add(obj.getReceivableOnewayReceivedClean());
                countingTicket = countingTicket.add(obj.getCountingTicket());
                dailyTicket = dailyTicket.add(obj.getDailyTicket());
                commemorativeTicket = commemorativeTicket.add(obj.getCommemorativeTicket());
                catSystemClean = catSystemClean.add(obj.getCatSystemClean());
                catAgreeClean =  catAgreeClean.add(obj.getCatAgreeClean());
                catSubtotal = catSubtotal.add(obj.getCatSubtotal());
                trafficCardSystemClean = trafficCardSystemClean.add(obj.getTrafficCardSystemClean());
                trafficCardAgreeClean = trafficCardAgreeClean.add(obj.getTrafficCardAgreeClean());
                trafficCardCatSubtotal = trafficCardCatSubtotal.add(obj.getTrafficCardCatSubtotal());
                qrCodeTicket = qrCodeTicket.add(obj.getQrCodeTicket());
                systemClean = systemClean.add(obj.getSystemClean());
                qrCodeTicketAgreeClean = qrCodeTicketAgreeClean.add(obj.getQrCodeTicketAgreeClean());
                qrSubtotal = qrSubtotal.add(obj.getQrSubtotal());
                faceTicketCcb = faceTicketCcb.add(obj.getFaceTicketCcb());
                faceTicketSystemClean =  faceTicketSystemClean.add(obj.getFaceTicketSystemClean());
                faceTicketAgreeClean = faceTicketAgreeClean.add(obj.getFaceTicketAgreeClean());
                faceSubtotal = faceSubtotal.add(obj.getFaceSubtotal());
                incomeSubtotal = incomeSubtotal.add(obj.getIncomeSubtotal());
                systemCleanSum = systemCleanSum.add(obj.getSystemCleanSum());
                systemCleanSumRatio = systemCleanSumRatio.add(new BigDecimal(obj.getSystemCleanSumRatio().substring(0,obj.getSystemCleanSumRatio().length()-1)));
                paidinReceivable = paidinReceivable.add(obj.getPaidinReceivable());
                receivableAcc = receivableAcc.add(obj.getReceivableAcc());

                paidinPreticket = paidinPreticket.add(obj.getPaidinPreticket());
                paidinInternetTicket = paidinInternetTicket.add(obj.getPaidinInternetTicket());
                paidinOnewayTicket = paidinOnewayTicket.add(obj.getPaidinOnewayTicket());
                paidinLongPayment = paidinLongPayment.add(obj.getPaidinLongPayment());
                receivablePreticket = receivablePreticket.add(obj.getReceivablePreticket());
                receivableInternetTicket = receivableInternetTicket.add(obj.getReceivableInternetTicket());
                receivableOnewayTicket = receivableOnewayTicket.add(obj.getReceivableOnewayTicket());
                receivableOnewayFare = receivableOnewayFare.add(obj.getReceivableOnewayFare());
                receivableOnewayRefund = receivableOnewayRefund.add(obj.getReceivableOnewayRefund());
                receivableOnewayOffset = receivableOnewayOffset.add(obj.getReceivableOnewayOffset());
                payableOutClean = payableOutClean.add(obj.getPayableOutClean());
                payablePreticketClean = payablePreticketClean.add(obj.getPayablePreticketClean());
                payableOnewayClean = payableOnewayClean.add(obj.getPayableOnewayClean());
                payableOnewayCleanFare = payableOnewayCleanFare.add(obj.getPayableOnewayCleanFare());
                payableOnewayCleanOnlySale = payableOnewayCleanOnlySale.add(obj.getPayableOnewayCleanOnlySale());
                receivableOnewaySubTotal = receivableOnewaySubTotal.add(obj.getReceivableOnewaySubTotal());
                catTicketPay = catTicketPay.add(obj.getCatTicketPay());
                trafficCardPay = trafficCardPay.add(obj.getTrafficCardPay());
                qrConnectivitySubTotal = qrConnectivitySubTotal.add(obj.getQrConnectivitySubTotal());
                qrCodeSubTotal = qrCodeSubTotal.add(obj.getQrCodeSubTotal());

            }
        }

        sumViewCkClearAccountDetailSummary.setPaidinOnewaySum(paidinOnewaySum.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewaySum(receivableOnewaySum.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewayAccSum(receivableOnewayAccSum.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewayAgreeClean(receivableOnewayAgreeClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewayReceivedClean(receivableOnewayReceivedClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setCountingTicket(countingTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setDailyTicket(dailyTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setCommemorativeTicket(commemorativeTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setCatSystemClean(catSystemClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setCatAgreeClean(catAgreeClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setCatSubtotal(catSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setTrafficCardSystemClean(trafficCardSystemClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setTrafficCardAgreeClean(trafficCardAgreeClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setTrafficCardCatSubtotal(trafficCardCatSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setQrCodeTicket(qrCodeTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setSystemClean(systemClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setQrCodeTicketAgreeClean(qrCodeTicketAgreeClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setQrSubtotal(qrSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setFaceTicketCcb(faceTicketCcb.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setFaceTicketSystemClean(faceTicketSystemClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setFaceTicketAgreeClean(faceTicketAgreeClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setFaceSubtotal(faceSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setIncomeSubtotal(incomeSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setSystemCleanSum(systemCleanSum.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setSystemCleanSumRatio((systemCleanSumRatio.setScale(2,BigDecimal.ROUND_HALF_UP))+"%");
        sumViewCkClearAccountDetailSummary.setPaidinReceivable(paidinReceivable.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableAcc(receivableAcc.setScale(2,BigDecimal.ROUND_HALF_UP));

        sumViewCkClearAccountDetailSummary.setPaidinPreticket(paidinPreticket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPaidinInternetTicket(paidinInternetTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPaidinOnewayTicket(paidinOnewayTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPaidinLongPayment(paidinLongPayment.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivablePreticket(receivablePreticket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableInternetTicket(receivableInternetTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewayTicket(receivableOnewayTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewayFare(receivableOnewayFare.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewayRefund(receivableOnewayRefund.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewayOffset(receivableOnewayOffset.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPayableOutClean(payableOutClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPayablePreticketClean(payablePreticketClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPayableOnewayClean(payableOnewayClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPayableOnewayCleanFare(payableOnewayCleanFare.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setPayableOnewayCleanOnlySale(payableOnewayCleanOnlySale.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setReceivableOnewaySubTotal(receivableOnewaySubTotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setCatTicketPay(catTicketPay.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setTrafficCardPay(trafficCardPay.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setQrConnectivitySubTotal(qrConnectivitySubTotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkClearAccountDetailSummary.setQrCodeSubTotal(qrCodeSubTotal.setScale(2,BigDecimal.ROUND_HALF_UP));

        return sumViewCkClearAccountDetailSummary;
    }

    @Override
    public void export(String startDate,String endDate,String operators,String lineCode,HttpServletResponse response) {

        List<ViewCkClearAccountDetailSummary> records = listViewCkClearAccountDetailSummary(startDate,endDate,operators,lineCode);
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("清分对账明细汇总表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkClearAccountDetailSummaryExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", startDate);
            map.put("endTime", endDate);
            if(CollectionUtils.isNotEmpty(records)){
                WriteSheet writeSheet = EasyExcel.writerSheet(0,"清分对账明细汇总表").build();
                // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
                // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
                // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
                // 如果数据量大 list不是最后一行 参照另一个
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
                excelWriter.fill(records, fillConfig, writeSheet);
                excelWriter.fill(map, writeSheet);
            }
            if(CollectionUtils.isNotEmpty(records)){
                WriteSheet writeSheet = EasyExcel.writerSheet(1,"清分对账明细表").build();
                // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
                // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
                // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
                // 如果数据量大 list不是最后一行 参照另一个
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
                excelWriter.fill(records, fillConfig, writeSheet);
                excelWriter.fill(map, writeSheet);
            }
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出清分对账明细汇总表异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
